package service

import (
	"booknote/bean"
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

func Openmysql() []bean.Book {
	//打开数据库
	//DSN数据源字符串：用户名:密码@协议(地址:端口)/数据库?参数=参数值
	db, _ := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/booknote?charset=utf8")

	//	if err != nil {
	//		fmt.Println("---can not open mysql-booknote---")
	//		return
	//	}
	fmt.Println("---open mysql-booknote---")
	//关闭数据库，db会被多个goroutine共享，可以不调用
	defer db.Close()

	//查询数据，指定字段名，返回sql.Rows结果集
	var books []bean.Book

	id := 0
	bookName := ""
	author := ""
	userId := ""
	summary := ""

	rows3 := db.QueryRow("select id,bookName, author, userId, summary from book where id = ?", 2)
	rows3.Scan(&id, &bookName, &author, &userId, &summary)
	fmt.Println(id, bookName, author, userId, summary)

	rows, _ := db.Query("select id,bookName, author, userId, summary from book")
	for rows.Next() {
		var book bean.Book

		rows.Scan(&id, &book.BookName, &book.Author, &book.UserId, &book.Summary)
		fmt.Println(id, book.BookName, book.Author, book.UserId, book.Summary)
		books = append(books, book)
	}

	return books

	//	stmt, _ := db.Prepare("select id,bookName from book where id = ?")
	//	rows4, _ := stmt.Query(3)
	//	//注意这里需要Next()下，不然下面取不到值
	//	rows4.Next()
	//	rows4.Scan(&id, &bookName)
	//	fmt.Println(id, bookName)

	//	rows, _ := db.Prepare("select * from userinfo")
	//	rows4, _ := rows.Query(1)

	//	id := 0
	//	bookName := ""
	//	rows4.Next()
	//	rows4.Scan(&id, &bookName)
	//	fmt.Println(id, bookName)

	//	for rows4.Next() {
	//		rows4.Scan(&id, &bookName)
	//		fmt.Println(id, bookName)
	//	}
}
